/*
 * VHSeasonSelector.java
 * Created on 16 juil. 2009
 *
 * VirtualHockey Internet Platform
 * http://code.google.com/p/virtualhockey/
 *
 * Copyright (c) 2005-2009, Jens and Jan Janke (VirtualHockey Project)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 */

package com.hockeo.vhweb.client.ui.widget;

import java.util.List;

import com.extjs.gxt.ui.client.Style.SortDir;
import com.hockeo.vhweb.client.rpc.VHRpcResultReceiver;
import com.hockeo.vhweb.client.ui.base.VHSelector;
import com.hockeo.vhweb.client.utils.VHJsData;

/**
 * Displays a list of seasons.
 *
 * @version $Id$
 * @author jjanke
 */
public class VHSeasonSelector extends VHSelector implements VHRpcResultReceiver<List<VHJsData>>
{
  public VHSeasonSelector()
  {
    getCombobox().setDisplayField( "name" );
    getCombobox().setValueField( "id" );
    getCombobox().setWidth( 200 );
  }

  /**
   * Sets the provided seasons to the internal store.
   */
  public void setRpcData( List<VHJsData> listSeasons, String strPurpose )
  {
    VHJsData seasonSelected = null;

    // select the last season for which data is available (reverse loop because list of seasons
    // is normally sorted descendingly, i.e. the most recent season first)
    //
    for ( int i = listSeasons.size() - 1; i >= 0; i-- )
    {
      VHJsData season = listSeasons.get( i );

      if ( seasonSelected == null || season.getBoolean( "dataAvailable" ) )
        seasonSelected = season;
    }

    if ( seasonSelected == null && !listSeasons.isEmpty() )
      seasonSelected = listSeasons.get( 0 );

    getStore().removeAll();
    getStore().add( listSeasons );

    // sort descendingly to have the last available season appear first in the list
    //
    getStore().sort( "id", SortDir.DESC );

    // Select active season
    //
    if ( !listSeasons.isEmpty() )
      getCombobox().setValue( seasonSelected );

    setInitialised( true );
  }
}
